import os.path
import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support import expected_conditions as EC


def get_all_url(driver):
    driver.get('https://101.qq.com/#/hero')

    all_card = driver.find_elements(By.CLASS_NAME, 'list-item')
    all_url = {}
    for card in all_card:
        url = card.find_element(By.TAG_NAME, 'a').get_attribute('href')
        all_url[card.text] = url + "&tab=skin"
    return all_url


class Hero:

    """保存所有的英雄图片"""

    def __init__(self, name, url, driver):
        self.name = name
        self.url = url
        self.driver = driver
        self.skin_url = {}

    def into_detail(self):
        self.driver.get(self.url)
        print(f'现在点击{self.name}的皮肤预览按钮！')
        link = self.driver.find_element(By.LINK_TEXT, '皮肤详情')
        link.click()
        print(f'已点击{self.name}的皮肤预览按钮！')

    def get_all_skins_url(self):
        self.driver.get(self.url)
        imgs = self.driver.find_elements(By.XPATH, '//div[@class="thumbs-con"]//div//div//img')
        print(f'正在获取{self.name}的所有皮肤地址。。。')
        for img in imgs:
            name = img.get_attribute('alt').replace(' ', '-')
            url = img.get_attribute('src')
            self.skin_url[name] = url
        print(f'已经获取到{self.name}的所有皮肤地址！')
        # print(self.skin_url)
        return self.skin_url

    def save(self):
        for k, v in self.skin_url.items():
            print(f'现在准备下载{k}。。。')
            self.driver.get(v)
            time.sleep(1)
            dirs = f'lolHerosImages/{self.name}/'
            if not os.path.exists(dirs):
                os.makedirs(dirs)
            try:
                self.driver.find_element(By.TAG_NAME, 'img').screenshot(os.path.join(dirs, f"{k}.png"))
            except:
                with open(os.path.join(dirs, f"下载失败-{k}.txt"), 'w') as file:
                    file.write('大概是404，官网没图！！')

            print(f'{k}下载成功！')


if __name__ == '__main__':
    driver = webdriver.Chrome(ChromeDriverManager().install())
    driver.maximize_window()
    driver.implicitly_wait(5)  # 页面级别最多等待5秒
    print('get all heros url!!!')
    all_url = get_all_url(driver)
    print(all_url)
    print('get all heros url!!! --- ok!')

    for name, url in all_url.items():
        someone = Hero(name, url, driver)
        # someone.into_detail()  # url拼接后不用次步骤
        someone.get_all_skins_url()
        someone.save()
    driver.quit()
